# -*- coding: utf-8 -*-
'''
Created on 2013-4-11

@author: cl.lam
'''
import flask
from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request, abort
from flask.blueprints import Blueprint

from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, mypaginate, \
    allPermission
from sys2do.util.logic_helper import getOption, getCurrentShopProfile
from sys2do.model import qry, Shop, InventoryProduct, Product, InventoryLocation, RGN
from sqlalchemy.sql.expression import and_, desc
from sys2do.util.common import _gl, _g
from sys2do.constant import *



__all__ = ['bpRg']


bpRg = Blueprint( 'bpRg', __name__, )

class ReturnGoodsView( BasicView ):

    template_folder = 'rg'

    @templated( "index.html" )
    @mypaginate( 'result' )
    @allPermission( ['RGN_VIEW'] )
    def index( self ):
        if request.method == 'POST':
            form = SrhForm( request.form )
            session[url_for( '.view' )] = form
        else:
            form = session.get( url_for( '.view' ), SrhForm( request.form ) )
        form.url = url_for( '.view' )

        if request.method != 'POST':
            return {'form' : form, 'result' : []}

        spobj = getCurrentShopProfile()
        cds = [ RGN.active == 0, RGN.shopID == spobj.shopID ]
        if form.no.data : cds.append( RGN.no.like( '%%%s%%' % form.no.data ) )
        if form.createTimeFrom.data : cds.append( RGN.createTime > form.createTimeFrom.data )
        if form.createTimeTo.data : cds.append( RGN.createTime < form.createTimeTo.data )

        result = RGN.iall( conditions = cds, order_by = desc( RGN.createTime ) )
        return {'form' : form, 'result' : result}


    @templated( 'add.html' )
    def add( self ):
        pdtIDs = _gl( 'pdt' )
        if not pdtIDs :
            flash( MSG_NOT_ENOUGH_PARAMS, MESSAGE_ERROR )
            return redirect( url_for( '.view', action = 'searchpdt' ) )
        if type( pdtIDs ) != list : pdtIDs = [pdtIDs, ]
        result = qry( InventoryProduct ).filter( and_( InventoryProduct.active == 0 , InventoryLocation.active == 0,
                                          InventoryProduct.ivtID == InventoryLocation.id,
                                          InventoryProduct.pdtID.in_( pdtIDs ),
                                          InventoryLocation.name == 'SOULD_OUT',
                                            ) ).count()

        if result != len( pdtIDs ) :
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            return redirect( url_for( '.view', action = 'searchpdt' ) )

        #=======================================================================
        # to be continue ,but need to finish the FIN first
        #=======================================================================




    @templated( "searchpdt.html" )
    def searchpdt( self ):
        form = SrhPdtForm( request.form )
        form.url = url_for( '.view', action = 'searchpdt' )
        if request.method != 'POST':
            return {'form' : form, 'records' : []}

        cds = [Product.active == 0 , InventoryProduct.active == 0 , InventoryLocation.active == 0, Shop.active == 0,
               InventoryProduct.pdtID == Product.id, InventoryProduct.ivtID == InventoryLocation.id,
               InventoryLocation.referID == Shop.id,
               ]
        result = qry( Product, Shop, InventoryProduct ).filter( and_( *cds ) ).order_by( Shop.name )
        return {'form' : form, 'records' : result}



    def viewRelated( self ):
        pass



    @templated( 'view_log.html' )
    def viewLog( self ):
        id = _g( 'id' )
        if not id : abort( 404 )
        obj = RGN.get( id )
        if not obj : abort( 404 )
        return {'obj' : 'obj'}


bpRg.add_url_rule( '/', view_func = ReturnGoodsView.as_view( 'view' ), defaults = {'action':'index'} )
bpRg.add_url_rule( '/<action>', view_func = ReturnGoodsView.as_view( 'view' ) )



#===============================================================================
# form class
#===============================================================================

from wtforms import Form, TextField, SelectField, DateField
from sys2do.util.wt_helper import MyDateField

class SrhForm( Form ):
    no = TextField( u'系统编号', )

    createTimeFrom = MyDateField( u'创建时间(开始)' )
    createTimeTo = MyDateField( u'创建时间(结束)' )


class SrhPdtForm( Form ):

    pdtno = TextField( u'商品编号', )
    pdtbarcode = TextField( u'商品条码', )
    pdtname = TextField( u'商品名称', )
#    shopID = SelectField(u'店铺名称',choices=getOption(Shop,[Shop.active==0,],Shop.name))
    spname = TextField( u'店铺名称', )
    createTimeFrom = MyDateField( u'卖出时间(开始)' )
    createTimeTo = MyDateField( u'卖出时间(结束)' )

